<?php

namespace App\Http\Controllers\Admin;

use App\Models\Bookcase;
use App\Models\BookcaseExhibition;
use App\Models\Manage;
use App\Validate\BookcaseValidate;
use Illuminate\Support\Facades\DB;

/**
 *  机柜管理
 */
class BookcaseController extends CommonController
{
    public $bookcaseModelObj = null;
    public $validateObj = null;

    public function __construct()
    {
        parent::__construct();

        $this->validateObj = new BookcaseValidate();
        $this->bookcaseModelObj = new Bookcase();
    }

    /**
     * 书柜列表
     * @param keyword 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param is_config 是否配置展览  0或空表示全部  1 已配置 2未配置，
     * @param except_ids 排除作品id  空或 0 表示不排除  多个逗号拼接
     */
    public function bookcaseList()
    {
        $keyword = $this->request->input('keyword', '');
        $start_time = $this->request->input('start_time', '');
        $end_time = $this->request->input('end_time', '');
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);
        $is_config = $this->request->input('is_config', '0');
        $except_ids = $this->request->input('except_ids' , '0');


        $res = $this->bookcaseModelObj->select(['id', 'name', 'cab_code', 'stack_number', 'address', 'intro', 'is_config', 'manage_id', 'create_time'])
            ->where(function ($query) use ($start_time, $end_time, $is_config,$except_ids) {
                if ($is_config) {
                    $query->where('is_config', $is_config);
                }

                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
                if($except_ids){
                    $except_ids = explode(',' , $except_ids);
                    $query->whereNotIn('id' , $except_ids);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('cab_code', 'like', '%' . $keyword . '%')
                        ->orWhere('stack_number', 'like', '%' . $keyword . '%');
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            $res = $this->disPageData($res);
            foreach ($res['data'] as $key => $val) {
                //获取所有的展览名
                if ($val['is_config'] == 1) {
                    $bookcaseExhibitionModelObj = new BookcaseExhibition();
                    $exhibition_info = $bookcaseExhibitionModelObj->getExhibitionAll($val['id']);
                    if($exhibition_info){
                        $exhibition_info = $exhibition_info->toArray();
                        $exhibition_info_name = array_column($exhibition_info, 'name');
                        $res['data'][$key]['exhibition_name'] = join(',', $exhibition_info_name);
                        $production_info = $bookcaseExhibitionModelObj->getExhibitionAllProductionName($val['id']);
                        $res['data'][$key]['production_number'] = count($production_info);
                    }else{
                        $res['data'][$key]['exhibition_name'] =   null;
                        $res['data'][$key]['production_number'] = 0;
                    }
                } else {
                    $res['data'][$key]['exhibition_name'] = null;
                    $res['data'][$key]['production_number'] = 0;
                }

                if ($val['manage_id']) {
                    $manageModelObj = new Manage();
                    $res['data'][$key]['manage_name'] = $manageModelObj->getManageNameByManageId($val['manage_id']);
                } else {
                    $res['data'][$key]['manage_name'] = null;
                }
            }

            //增加序号
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 书柜列表（用于 展览 筛选）
     * @param keyword 筛选条件
     * @param exhibition_id 展览id  （用于判断此展览是否在书柜显示）
     */
    public function bookcaseFilterList()
    {
        $keyword = $this->request->input('keyword', '');
        $exhibition_id = $this->request->input('exhibition_id', '');
        $res = $this->bookcaseModelObj->select(['id', 'name', 'stack_number'])
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('cab_code', 'like', '%' . $keyword . '%')
                        ->orWhere('stack_number', 'like', '%' . $keyword . '%');
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->get();

        if ($res) {
            //获取展览对应的所有的书柜id
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcase_ids = $bookcaseExhibitionModelObj->getBookcaseIdByExhibitionId($exhibition_id);
            foreach ($res as $key => $val) {
                if ($exhibition_id) {
                    //判断是否选择
                    if (in_array($val['id'], $bookcase_ids)) {
                        $res[$key]['selected'] = true;
                    } else {
                        $res[$key]['selected'] = false;
                    }
                } else {
                    $res[$key]['selected'] = false;
                }
            }

            return $this->returnApi(200, '获取成功', true, $res);
        }


        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 机柜详情
     * @param id 机柜id
     */
    public function bookcaseInfo()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        $res = $this->bookcaseModelObj->select(['id', 'name', 'cab_code', 'stack_number', 'address', 'intro', 'is_config', 'create_time'])->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '获取失败');
        }

        //获取所有的展览名
        if ($res['is_config'] == 1) {
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $exhibition_info = $bookcaseExhibitionModelObj->getExhibitionAll($res['id']);
            $res['exhibition_info'] = $exhibition_info;
            $production_info = $bookcaseExhibitionModelObj->getExhibitionAllProductionName($res['id']);
            $res['production_number'] = count($production_info);
        } else {
            $res['exhibition_info'] = [];
            $res['production_number'] = 0;
        }

        if ($res['manage_id']) {
            $manageModelObj = new Manage();
            $res['manage_name'] = $manageModelObj->getManageNameByManageId($res['manage_id']);
        } else {
            $res['manage_name'] = null;
        }

        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 机柜添加
     * @param name 机柜名称    必选
     * @param address 机柜地址
     * @param intro 机柜简介
     * @param exhibition_id 作品id （所有的展览id） 多个 逗号 分隔   空表示清空 书柜
     */

    public function bookcaseAdd()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $is_exists = $this->bookcaseModelObj->bookcaseNameIsExists($this->request->name);
        if ($is_exists) {
            return $this->returnApi(202, '此名称已存在，请重新添加');
        }

        DB::beginTransaction();
        try {
            $res = $this->bookcaseModelObj->add($this->request);
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->bookcaseExhibitionChange($this->bookcaseModelObj->id, $this->request->exhibition_id, 'add');

            //修改机柜配置展览信息
            $bookcaseModelObj = new Bookcase();
            $bookcaseModelObj->isConfigChange($this->bookcaseModelObj->id);

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '添加失败');
        }
    }

    /**
     * 机柜修改
     * @param id  机柜id  必选
     * @param name 机柜名称    必选
     * @param address 机柜地址
     * @param intro 机柜简介
     * @param exhibition_id 作品id （所有的展览id） 多个 逗号 分隔   空表示清空 书柜
     */

    public function bookcaseChange()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        $is_exists = $this->bookcaseModelObj->bookcaseNameIsExists($this->request->name, $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, '此名称已存在，请重新修改');
        }


        DB::beginTransaction();
        try {
            $res = $this->bookcaseModelObj->change($this->request);

            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->bookcaseExhibitionChange($this->request->id, $this->request->exhibition_id, 'change');

            //修改机柜配置展览信息
            $bookcaseModelObj = new Bookcase();
            $bookcaseModelObj->isConfigChange($this->request->id);

            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }

    /**
     * 机柜 配置 展览
     * @param id 机柜id
     * @param exhibition_id 展览id （所有的展览id） 多个 逗号 分隔   空表示清空 展览
     */
    public function bookcaseConfigExhibition()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_config_exhibition')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $exhibition_id = $this->request->exhibition_id;

        $res = $this->bookcaseModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '配置失败');
        }

        DB::beginTransaction();
        try {
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->bookcaseExhibitionChange($res->id, $exhibition_id, 'change');

            //修改机柜配置展览信息
            $bookcaseModelObj = new Bookcase();
            $bookcaseModelObj->isConfigChange($res->id);

            DB::commit();
            return $this->returnApi(200, '配置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '配置失败');
        }
    }

    /**
     * 机柜 添加 展览
     * @param id 机柜id
     * @param exhibition_id 展览id （需要添加的展览id） 多个 逗号 分隔 
     */
    public function bookcaseAddExhibition()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_add_exhibition')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $exhibition_id = $this->request->exhibition_id;

        $res = $this->bookcaseModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '添加失败');
        }

        DB::beginTransaction();
        try {
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->bookcaseExhibitionAdd($res->id, $exhibition_id);

            //修改机柜配置展览信息
            $bookcaseModelObj = new Bookcase();
            $bookcaseModelObj->isConfigChange($res->id);

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '添加失败');
        }
    }

    /**
     * 机柜 删除 展览
     * @param id 机柜id
     * @param exhibition_id 展览id （需要删除的展览id） 多个 逗号 分隔
     */
    public function bookcaseDelExhibition()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_del_exhibition')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $exhibition_id = $this->request->exhibition_id;

        $res = $this->bookcaseModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '删除失败');
        }

        DB::beginTransaction();
        try {
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->bookcaseExhibitionDel($res->id, $exhibition_id);

            //修改机柜配置展览信息
            $bookcaseModelObj = new Bookcase();
            $bookcaseModelObj->isConfigChange($res->id);

            DB::commit();
            return $this->returnApi(200, '删除成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '删除失败');
        }
    }

    /**
     * 机柜删除
     * @param id  机柜id  必选
     */

    public function bookcaseDel()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('bookcase_del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        //判断机柜是否有展览
        $bookcaseExhibition = new BookcaseExhibition();
        $is_exhibition = $bookcaseExhibition->bookcaseIsExhibition($this->request->id);
        if ($is_exhibition) {
            return $this->returnApi(202, '此机柜正式展示《' . $is_exhibition . '》，请先取消后在进行删除');
        }

        $res = $this->bookcaseModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '删除失败');
        }
        $res->is_del = 2;
        $result = $res->save();

        if ($result) {
            return $this->returnApi(200, '删除成功', true);
        }

        return $this->returnApi(202, '删除失败');
    }
}
